<script setup>
import { ref, onUnmounted, nextTick } from "vue";
import { login, send, mini } from "@/services/login";
import { useUserStore } from "@/stores/user.js";
import { userloginStore } from "@/stores/islogin.js";

import { skip } from "@/services/user";
import { onLoad } from "@dcloudio/uni-app";
import { isMobile } from "@/utils/isMobile";
import { productinfo } from "@/services/thali";
import { handleGoBack } from "@/utils/router";
import loginto from "@/utils/reder.js";

// import { share } from "@/utils/share.js";
// if (uni.getStorageSync("outlogin")) {
//   uni.removeStorageSync("outlogin");
//   loginto();
// }

const popup = ref(null);

const user = useUserStore();
const userlogin = userloginStore();
const linkobj = ref({});

// 获取组件实例
const formRef = ref(null);
const queryobj = ref(null);
const valiFormData = ref({
  phone: "",
  code: "",
  referrer_id: "",
});

const jzsr = ref(false);

onLoad((query) => {
  console.log(query);
  // #ifdef H5
  if (!uni.getStorageSync("Authorization")) {
    loginto(query);
  }
  // #endif
  queryobj.value = query;

  if (query.referrer_id) {
    uni.setStorageSync("referrer_id", query.referrer_id);
  }
  // earnCountfun();
  if (query.referrer_id) {
    valiFormData.value.referrer_id =
      query.referrer_id > 0 ? query.referrer_id : "";
    jzsr.value = false;
    logintype.value = 2;

    return;
  } else {
    logintype.value = 1;

    jzsr.value = false;
  }

  if (!query.referrer_id && uni.getStorageSync("referrer_id")) {
    logintype.value = 2;
    jzsr.value = false;
    valiFormData.value.referrer_id = uni.getStorageSync("referrer_id");
  } else {
    logintype.value = 1;
    jzsr.value = false;
  }

  queryobj.value.isMobile = isMobile();
});

// async function earnCountfun() {
//   let reslink = await skip();
//   linkobj.value = reslink.data;
// }
/* 基础表单数据 */

const valiForm = ref(null);

// 验证表单数据的规则
const formRules = {
  phone: {
    rules: [
      {
        required: true,
        errorMessage: "请填写手机号码",
      },
      {
        pattern: "^1\\d{10}$",
        errorMessage: "手机号码格式不正确",
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
      {
        pattern: /^\S{6}$/,
        errorMessage: "请输入6位数验证码",
      },
    ],
  },
  // referrer_id: {
  //   rules: [
  //     {
  //       required: true,
  //       errorMessage: "请输入推荐人信息",
  //     },
  //   ],
  // },
};

/* 手机号校验规则*/
const rules = ref({
  phone: {
    rules: [
      {
        required: true,
        errorMessage: "手机号不能为空",
      },
      {
        validateFunction: function (rule, value, data, callback) {
          let iphoneReg = /^1\d{10}$/; //手机号码
          if (!iphoneReg.test(value)) {
            ts(1);
            callback("手机号码格式不正确，请重新填写");
          }
        },
      },
    ],
  },

  code: {
    rules: [
      {
        required: true,
        errorMessage: "手机验证码不能为空",
      },
    ],
  },
});

const shareindex = () => {};

async function getuserinfofun() {
  pagesurl();
}
// 跳转页面
async function formSubmit() {
  var Messagedata = null;
  // #ifdef H5

  if (!valiFormData.value.phone || !valiFormData.value.code) {
    return;
  }
  valiFormData.value.ssid = uni.getStorageSync("ssid")
    ? uni.getStorageSync("ssid")
    : "";
  // if (logintype.value == 2 && !valiFormData.value.referrer_id) {
  //   uni.showToast({
  //     title: "请输入推荐人信息",
  //     icon: "none",
  //   });

  //   return;
  // }
  try {
    valiForm.value
      .validate()
      .then(async (res) => {
        uni.removeStorageSync("jwt-token");
        if (logintype.value == 1) {
          valiFormData.value.referrer_id = 0;
        }

        const datas = await login(valiFormData.value);
        if (datas.code === 200) {
          uni.setStorageSync("userInfo", datas.result);
          uni.setStorageSync("loginType", logintype.value);
          uni.setStorageSync("Authorization", datas.data.token.token);
          uni.setStorageSync("version", "v1");
          uni.removeStorageSync("referrer_id");
          userlogin.setlogin(true);
          uni.showToast({
            title: "登录成功",
            icon: "none",
            mask: true,
          });
          pagesurl();
        } else {
        }
      })
      .catch((err) => {
        Messagedata = err.info
          ? err.info
          : err[0].errorMessage
          ? "手机号格式不对"
          : "";
        uni.showToast({
          title: Messagedata,
          icon: "none",
          mask: true,
        });
      });

    // 临时跳转到首页面
  } catch (e) {
    //TODO handle the exception
  }
  // #endif

  // #ifdef MP-WEIXIN

  if (!valiFormData.value.phone || !valiFormData.value.code) {
    return;
  }
  valiFormData.value.ssid = uni.getStorageSync("ssid")
    ? uni.getStorageSync("ssid")
    : "";
  if (checked.value) {
    wx.login({
      async success(res2) {
        if (res2.code) {
          //发起网络请求
          console.log(res2.code);

          try {
            valiForm.value
              .validate()
              .then(async (res) => {
                uni.removeStorageSync("jwt-token");
                const wxres = await mini({ code: res2.code });
                console.log(wxres);
                valiFormData.value.m_ssid = wxres.data.m_ssid;
                const datas = await login(valiFormData.value);
                if (datas.code === 200) {
                  uni.setStorageSync("userInfo", datas.result);
                  uni.setStorageSync("loginType", logintype.value);
                  uni.setStorageSync("Authorization", datas.data.token.token);
                  uni.setStorageSync("version", "v1");
                  userlogin.setlogin(true);
                  uni.showToast({
                    title: "登录成功",
                    icon: "none",
                    mask: true,
                  });
                  pagesurl();
                  if (uni.getStorageSync("referrer_id")) {
                    uni.removeStorageSync("referrer_id");
                  }
                } else {
                }
              })
              .catch((err) => {
                Messagedata = err.info
                  ? err.info
                  : err[0].errorMessage
                  ? "手机号格式不对"
                  : "";
                uni.showToast({
                  title: Messagedata,
                  icon: "none",
                  mask: true,
                });
              });

            // 临时跳转到首页面
          } catch (e) {
            //TODO handle the exception
          }
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      },
    });
  } else {
    uni.showToast({
      title: "请勾选阅读并同意《用户隐私保护指引》！",
      icon: "none",
    });
    return;
  }

  // #endif

  // #ifdef APP-PLUS

  if (!valiFormData.value.phone || !valiFormData.value.code) {
    return;
  }
  valiFormData.value.ssid = uni.getStorageSync("ssid")
    ? uni.getStorageSync("ssid")
    : "";
  if (checked.value) {
    try {
      valiForm.value
        .validate()
        .then(async (res) => {
          uni.removeStorageSync("jwt-token");
          if (logintype.value == 1) {
            valiFormData.value.referrer_id = 0;
          }

          const datas = await login(valiFormData.value);
          if (datas.code === 200) {
            uni.setStorageSync("userInfo", datas.result);
            uni.setStorageSync("loginType", logintype.value);
            uni.setStorageSync("Authorization", datas.data.token.token);
            uni.setStorageSync("version", "v1");
            uni.removeStorageSync("referrer_id");
            userlogin.setlogin(true);
            uni.showToast({
              title: "登录成功",
              icon: "none",
              mask: true,
            });
            pagesurl();
          } else {
          }
        })
        .catch((err) => {
          Messagedata = err.info
            ? err.info
            : err[0].errorMessage
            ? "手机号格式不对"
            : "";
          uni.showToast({
            title: Messagedata,
            icon: "none",
            mask: true,
          });
        });

      // 临时跳转到首页面
    } catch (e) {
      //TODO handle the exception
    }
  } else {
    uni.showToast({
      title: "请勾选阅读并同意《用户隐私保护指引》！",
      icon: "none",
    });
    return;
  }

  // #endif
}

const gonhoneshopfun = () => {
  getuserinfofun();
};

function pagesurl() {
  if (getCurrentPages().length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({
      url: "/pages/index/index",
    });
  }
}

//认证码模块
let timeget = null;
const timenum = ref(60);
const codedisabled = ref(false);
const logintype = ref(1);

/* 发送手机号 */
const getcodes = async () => {
  if (codedisabled.value) {
    return;
  }
  valiForm.value
    .validateField(["phone"])
    .then(async (ress) => {
      codedisabled.value = true;

      timeget = setInterval(function () {
        timenum.value--;
        if (timenum.value <= 0) {
          codedisabled.value = false;
          clearInterval(timeget);
          timenum.value = 60;
        }
      }, 1000);
      try {
        uni.removeStorageSync("jwt-token");
        const res = await send({
          phone: valiFormData.value.phone,
        });
        if (res.code == 200) {
          uni.showToast({
            title: "发送成功",
            icon: "none",
          });
        } else {
          uni.showToast({
            title: "发送失败，请重试",
            icon: "none",
          });
        }
      } catch (e) {
        uni.showToast({
          title: e.info,
          icon: "none",
        });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: "手机号格式不正确",
        icon: "none",
      });
    });
};
onUnmounted(() => {
  // 做一些清理工作
  clearInterval(timeget);
});

/* 权限跳转 */
const goabout = (index) => {
  if (index === 2) {
    uni.navigateTo({
      url: "/pages/privacypolicy/index",
    });
  } else {
    uni.navigateTo({
      url: "/pages/userpermiss/index",
    });
  }
};
const checked = ref(false);

/* 勾选是否阅读权限 */
const checkboxfun = () => {
  checked.value = !checked.value;
  console.log("sdasasdasdasd", checked.value);
};

// #ifdef MP-WEIXIN || APP-PLUS
const title = ref("用户隐私保护提示");
const desc1 = ref("感谢您使用私语清韵小程序，您使用本小程序前应当阅读并同意");
const urlTitle = ref("《用户隐私保护指引》");
const desc2 = ref(
  "当您点击同意并开始时用产品服务时，即表示你已理解并同息该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法正常使用该小程序。"
);

if (uni.getPrivacySetting) {
  uni.getPrivacySetting({
    success: (res) => {
      if (res.needAuthorization) {
        nextTick(() => {
          setTimeout(() => {
            popup.value.open("center");
          }, 1);
        });
      } else {
      }
    },
    fail: () => {},
    complete: () => {},
  });
} else {
  // 低版本基础库不支持 wx.getPrivacySetting 接口，隐私接口可以直接调用
}
// #endif

const openPrivacyContract = () => {
  // #ifdef MP-WEIXIN
  uni.openPrivacyContract({
    success: (res) => {},
    fail: (res) => {
      console.error("openPrivacyContract fail", res);
    },
  });
  // #endif

  // #ifdef APP-PLUS
  uni.navigateTo({
    url: "/pages/mine/userAgreement",
  });
  // #endif
};
const handleAgree = () => {
  popup.value.close();
};
const handleDisagree = (e) => {
  popup.value.close();
  uni.navigateBack({
    delta: 1,
  });
};
const shopobj = ref({});
// const selectfun = async () => {
//   let res = await getproductinfo(queryobj.value.product_id);
//   shopobj.value = res.data;
//   shopshow.value = true;
// };
async function getproductinfo(id) {
  return await productinfo({ product_id: id });
}
function wxnurl(params, versions) {
  let paramsurl = params ? params : "pages/index/index";
  return `<wx-open-launch-weapp  class="launch-weapp" id="launch-btn" appid="wxbbb8ed3d5b5ada72" username="gh_d08f4ffdf5cc"  path="${paramsurl}${queryobj.value.product_id}" style=" z-index: 9999;position: absolute;top: 0; left: 0;display: block;width: 100%;height: 100%;opacity:0;overflow: hidden;" > \<script  type="text/wxtag-template" style="display: block; height: 170px; width: 100%; z-index: 99999;opacity:0;"\>\<button style="height: 170px; width: 100%; z-index: 99; display: block"\>点击跳转小程序\<\/button\>\<\/script\></wx-open-launch-weapp>`;
}
const shopshow = ref(false);

const logintypefun = () => {
  logintype.value == 1 ? (logintype.value = 2) : (logintype.value = 1);
};

const close = () => {};
const open = () => {};
</script>
<template>
  <view class="login">
    <view class="bg">
      <div class="ul-img"></div>
      <view class="ul">
        <view class="li">
          <image
            src="../../static/login/login_logo.png"
            mode="widthFix"
          ></image>
        </view>
      </view>
      <view class="login-item-title">{{
        logintype == 1 ? "手机验证码登录" : "手机码注册"
      }}</view>
    </view>

    <view class="login-bottom">
      <view class="mobile">
        <view class="form-k">
          <uni-forms
            ref="valiForm"
            :rules="rules"
            :modelValue="valiFormData"
            label-width="80"
          >
            <view class="imfrom-k">
              <view class="imfrom-k-icon">
                <image
                  src="../../static/login/login_phone.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="phone">
                <uni-easyinput
                  v-model="valiFormData.phone"
                  placeholder="请输入手机号码"
                />
              </uni-forms-item>
            </view>

            <view class="imfrom-k">
              <view class="imfrom-k-icon">
                <image
                  src="../../static/login/login_code.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="code">
                <view class="imfrom-k-yz">
                  <view class="imfrom-inputs">
                    <uni-easyinput
                      v-model="valiFormData.code"
                      placeholder="请输入验证码"
                    >
                      <template #right>
                        <view
                          :class="valiFormData.phone ? 'getcodes1' : 'getcodes'"
                          @click="getcodes"
                        >
                          <text :class="codedisabled ? 'selectcodes' : ''">{{
                            codedisabled
                              ? timenum + "s后重新获取"
                              : "获取验证码"
                          }}</text>
                        </view>
                      </template>
                    </uni-easyinput>
                  </view>
                </view>
              </uni-forms-item>
            </view>

            <view class="imfrom-k" v-if="logintype == 2">
              <view class="imfrom-k-icon">
                <image
                  src="../../static/login/login_phone.png"
                  mode="widthFix"
                />
              </view>
              <uni-forms-item label="" name="referrer_id">
                <uni-easyinput
                  v-model="valiFormData.referrer_id"
                  placeholder="推广id/手机号"
                  :disabled="jzsr"
                />
              </uni-forms-item>
            </view>
          </uni-forms>
        </view>
      </view>

      <!-- #ifdef MP-WEIXIN || APP-PLUS  -->
      <view class="checkbox">
        <up-checkbox-group>
          <up-checkbox
            v-model="checked"
            shape="circle"
            label="阅读并同意"
            activeColor="#f3498b"
            @change="checkboxfun"
          ></up-checkbox>
        </up-checkbox-group>
        <view class="login_urlTitle" @click="openPrivacyContract">
          {{ urlTitle }}
        </view>
      </view>
      <!-- #endif -->

      <!-- #ifdef H5 || APP-PLUS -->
      <button
        class="uni-button"
        :class="
          valiFormData.phone && valiFormData.code ? 'uni-button-cloor' : ''
        "
        @click="formSubmit"
      >
        {{ logintype == 1 ? "登录" : "注册" }}
        <!-- <wx-open-launch-weapp
          v-if="
            valiFormData.phone &&
            valiFormData.code &&
            queryobj.product_id &&
            queryobj.isMobile
          "
          @click="shareindex"
          id="launch-btn"
          class="launch-weapp"
          appid="wx2c119a1393644393"
          username="gh_658bb7bff80b"
          path="/pages/guide/index"
          style="z-index: 99; position: absolute; top: 0; left: 0"
        >
          <view
            v-is="'script'"
            type="text/wxtag-template"
            style="display: block; height: 170px; width: 100%; z-index: 99"
          >
            <button style="height: 170px; width: 100%; z-index: 99">
              点击跳转小程序
            </button>
          </view>
        </wx-open-launch-weapp> -->
      </button>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN  -->
      <button
        class="uni-button"
        :class="
          valiFormData.phone && valiFormData.code ? 'uni-button-cloor' : ''
        "
        @click="formSubmit"
      >
        {{ logintype == 1 ? "登录" : "注册" }}
      </button>
      <!-- #endif -->

      <!-- <view class="unilogin-dec">如何成为经销商？</view>  -->
      <view class="login-type">
        <text @click="logintypefun">{{
          logintype == 1 ? "注册" : "登录"
        }}</text>
      </view>
    </view>

    <!-- #ifdef MP-WEIXIN -->
    <!-- <view class="login-bottom">
      <view class="zc-rule"> </view>
      <button class="uni-button" @click="formSubmit">授权号授权</button>
    </view> -->
    <!-- #endif -->
  </view>

  <!-- #ifdef MP-WEIXIN  -->

  <uni-popup ref="popup" :animation="true" :is-mask-click="false">
    <view class="popup_content">
      <view class="popup_title">
        {{ title }}
      </view>
      <view class="popup_desc">
        {{ desc1 }}
      </view>
      <view class="popup_urlTitle" @click="openPrivacyContract">
        {{ urlTitle }}
      </view>
      <view class="popup_desc">
        {{ desc2 }}
      </view>
      <view class="popup_cz">
        <button
          id="disagree-btn"
          type="default"
          class="weui-btn"
          @click="handleDisagree"
        >
          不同意并退出
        </button>
        <button
          id="agree-btn"
          type="primary"
          open-type="agreePrivacyAuthorization"
          class="weui-btn"
          @agreeprivacyauthorization="handleAgree"
        >
          同意并继续
        </button>
      </view>
    </view>
  </uni-popup>
  <!-- #endif -->

  <up-popup
    :show="shopshow"
    :round="15"
    mode="center"
    @close="close"
    @open="open"
  >
    <view class="shopindex-k">
      <view class="shopindex-image">
        <image :src="shopobj && shopobj.image" mode="widthFix" />
      </view>

      <view class="store-name">{{ shopobj && shopobj.store_name }}</view>

      <view class="bt-foolr">
        <view class="bt-foolr-home" @click="gonhoneshopfun"> 首页 </view>
        <view class="bt-foolr-shop">
          <text>查看商品</text>
          <div
            v-if="linkobj && linkobj.ybt_mini_product"
            v-html="wxnurl(linkobj.ybt_mini_product, linkobj.versions)"
          ></div>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<style lang="scss" scoped>
@import "login.scss";
</style>
